<template>  
  <div class="stat-container">  
    <el-row :gutter="20">
      <el-col :span="4" class="stat-col">  
        <el-button type="primary" class="stat-button" style="background-color: #e6a23c;" @click="handleAdd">  
          <i slot="icon" class="el-icon-user" /> <!-- 假设这里使用不同的图标 -->  
          <div class="stat-text">  
            <div class="stat-label">总访问</div>  
            <div class="stat-number">232</div>  
          </div>  
        </el-button>  
      </el-col>

      <!--新增类别表单  -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item v-if="form.categoryId" label="类别id" prop="categoryId">
            <el-input v-model="form.categoryId" placeholder="请输入类别id" disabled />
          </el-form-item>
          <el-form-item label="类别名称" prop="categoryName">
            <el-input v-model="form.categoryName" placeholder="请输入名称" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>  
</template>

<script>
import { listCategoryByPage, delCategory, addCategory, getCategoryList, updateCategory } from '@/api/category'
export default {
  name: 'Category',
  data() {
    return {
        loading: false,
        categoryList: [],
        queryParams: { // 查询参数
        pageNum: 1,
        pageSize: 5,
        catgeoryName: null,
        categoryId: null
      },
        // categoryOptions:[],
        ids: [],
        multiple: true,
        single: false,
        title: '',
        open: false,
        total: 0,
        form: {},
      rules: {
        name: [
          { required: true, message: '请输入类别名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCategoryList()
    // this.getCategoryOptions();
  },
  methods: {
    getCategoryList(){
      this.loading = true
      listCategoryByPage(this.queryParams).then(response => {
        this.categoryList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },

    handleQuery(){
      this.queryParams.pageNum = 1
      this.getCategoryList()
    },
    resetQuery(){
      this.$refs.queryForm.resetFields()
      this.getCategoryList()
    },
    handleUpdate(row){
      this.resetForm()
      if (row) {
      this.form.categoryId = row.categoryId || this.ids[0]
    }
    this.open = true
    this.title = '修改数据'
    },
    handleDelete(row){
      const categoryId = row.categoryId || this.ids[0]
      this.$confirm('是否确认删除ID为"' + categoryId + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        return delCategory({ categoryId })
      })
      .then(() => {
        this.getCategoryList() // 刷新数据
        this.$message.success('删除成功')
      })
      .catch(() => {
    this.$message.error('删除失败')
})
    },
    handleSelectionChange(selection){
      this.ids = selection.map(item => item.categoryId)
      // eslint-disable-next-line eqeqeq
      this.single = selection.length == 1
      this.multiple = !selection.length
      console.log('Selected IDs:', this.ids)
    },
    resetForm(){
      this.form = {
        categoryId: null,
        categoryName: null
      }
    },

    handleAdd(){
      this.resetForm()
      this.open = true
      this.title = '添加数据'
    },
    submitForm: function(){
      this.$refs['form'].validate(valid => {
                if (valid){
          if (this.form.categoryId != null){
            updateCategory(this.form).then(response => {
              this.$message.success(response.msg)
              this.getCategoryList()
              this.cancel()
            })
          } else {
            addCategory({ categoryName: this.form.categoryName }).then(response => {
              this.$message.success(response.msg)
              this.getCategoryList()
              this.cancel()
            })
          }
        }
      })
    },
    cancel(){
      this.open = false
      this.title = ''
      this.resetForm()
    },
    handleSizeChange(val){
      this.queryParams.pageSize = val
      this.getCategoryList()
    },
    handleCurrentChange(val){
      this.queryParams.pageNum = val
      this.getCategoryList()
     },
      // 修改时间格式
    formatDateTime(dateTimeStr) {
      const date = new Date(dateTimeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0') // 月份是从0开始的，所以要加1
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
    }
   }
}


</script>